//
//  BDPubishLocationViewController.m
//  BadBoy
//
//  Created by wen on 2017/3/31.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDPubishLocationViewController.h"
#import <AMap2DMap-NO-IDFA/MAMapKit/MAMapKit.h>
#import "BDLocationServer.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import "BDUserModel.h"
#import "BDSearchResultsViewController.h"
@interface BDPubishLocationViewController ()<MAMapViewDelegate, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate,UISearchResultsUpdating,UISearchControllerDelegate, AMapSearchDelegate>
{
    NSInteger selectedRow;
    BOOL notNeedSetTableViewOffset;
    
    double currentLong;
    double currentLat;
}
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<AMapPOI *> *datasource;
//搜索控制器
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIImageView *pointImageView;
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) BDSearchResultsViewController *searchResultsController;
@property (nonatomic, strong) UITableView *topTableView;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;

@property (nonatomic, copy) void(^finishBlock)(AMapPOI *poi);

@end

@implementation BDPubishLocationViewController

- (instancetype)initWithFinishBlock:(void(^)(AMapPOI *poi))finishBlock{
    if (self = [super init]) {
        self.finishBlock = finishBlock;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = ASLocalizedString(@"选择位置");
    
    //topTableView(专门放置搜索框)
    self.topTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, self.view.bounds.size.width, 110) style:UITableViewStylePlain];
    self.topTableView.tableFooterView = [[UIView alloc] init];
    self.topTableView.scrollEnabled = NO;
    self.topTableView.tableHeaderView = self.searchController.searchBar;
    [self.view addSubview:self.topTableView];
    
    selectedRow = 0;
    BDLocationModel *model = [BDLocationModel getLocationInfo];
    self.mapView.centerCoordinate = CLLocationCoordinate2DMake(model.latitude, model.longitude);
    currentLong = model.longitude;
    currentLat = model.latitude;
    [self getCurrentLocationAddress];
    [self.view insertSubview:self.tableView atIndex:0];
    [self.view addSubview:self.mapView];
//    [self.view addSubview:self.searchBar];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:ASLocalizedString(@"完成")style:UIBarButtonItemStyleDone target:self action:@selector(doneButtonAction)];
    self.navigationItem.rightBarButtonItem = item;
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:ASLocalizedString(@"取消")style:UIBarButtonItemStyleDone target:self action:@selector(cancelButtonAction)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:SearchResultsControllerDidSelectRow object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        AMapPOI *poi = x.object;
        self.mapView.centerCoordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
        [self.datasource removeAllObjects];
        self.startPage = @"1";
        self.searchController.searchBar.text = nil;
        currentLong = poi.location.longitude;
        currentLat = poi.location.latitude;
        selectedRow = 0;
        self.tableView.hidden = YES;
        [self.indicatorView startAnimating];
        [self getCurrentLocationAddress];
        [self willDismissSearchController:self.searchController];
    }];
}

- (void)doneButtonAction{
    if (self.finishBlock) {
        AMapPOI *poi = self.datasource[selectedRow];
        self.finishBlock(poi);
    }
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)cancelButtonAction{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)getCurrentLocationAddress{
    CLLocation * location = [[CLLocation alloc] initWithLatitude:currentLat longitude:currentLong];
    CLGeocoder * geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error == nil && [placemarks count] > 0) {
            
            //这时的placemarks数组里面只有一个元素
            
            CLPlacemark * placemark = [placemarks firstObject];
            
            NSString *currentAddress = @"";
            
            if (placemark.administrativeArea) {
                currentAddress = [currentAddress stringByAppendingString:placemark.administrativeArea];
            }
            if (placemark.locality) {
                currentAddress = [currentAddress stringByAppendingString:placemark.locality];
            }
            if (placemark.subLocality) {
                currentAddress = [currentAddress stringByAppendingString:placemark.subLocality];
            }
            if (placemark.name) {
                currentAddress = [currentAddress stringByAppendingString:placemark.name];
            }
            AMapPOI *poi = [[AMapPOI alloc] init];
            poi.address = currentAddress;
            poi.location = [AMapGeoPoint locationWithLatitude:currentLat longitude:currentLong];
            poi.province = placemark.administrativeArea;
            poi.city = placemark.locality;
            poi.district = placemark.subLocality;
            [self.datasource addObject:poi];

            [self requestData];
        }
        
    }];
}

- (void)requestData{
    /*
     方案1：搜索地标建筑
     */
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:currentLat longitude:currentLong];
    /*
     type总的内容：
     汽车服务，汽车销售，汽车维修，摩托车服务，餐饮服务，购物服务，生活服务，体育休闲服务，医疗保健服务，住宿服务，风景名胜，商务住宅，政府机构及社会团体，科教文化服务，交通设置服务，金融保险服务，公司企业，道路附属设施，地名地址信息，公共设施
     */
    request.types = ASLocalizedString(@"风景名胜|商务住宅|政府机构及社会团体|交通设施服务|公司企业|道路附属设施|地名地址信息");
    request.sortrule = 0;
    request.requireExtension = YES;
    request.page = self.startPage.integerValue;
    [self.search AMapPOIAroundSearch:request];
    /*
     这里请求数据，应该根据当前建筑的中心点来，如果没有输入关键字的情况下，那么中心点是用户当前位置，如果拖动了，那么中心点是地图当前位置，如果输入关键字搜索回来了，那么中心点是通过关键字搜索到的商家
     */
//    NSString *city_id = [BDLocationServer getCity_id];
//    NSString *url = [NSString stringWithFormat:@"http://192.168.1.150/api/shops?page=%@&size=%@&order=1&user_lng=%f&user_lat=%f&city_id=%@", self.startPage, self.pageSize, currentLong, currentLat, city_id];
//    [self requestWithUrl:url];
}

#pragma mark -------------------------AMapSearch代理---------------------------------
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    if (response.pois.count == 0) {
        return;
    }
    [self.datasource addObjectsFromArray:response.pois];
    [self.tableView reloadData];
    [self.indicatorView stopAnimating];
    self.tableView.hidden = NO;
    self.startPage = [NSString stringWithFormat:@"%ld", (self.startPage.integerValue + 1)];
    
    if (notNeedSetTableViewOffset == NO && self.tableView.contentOffset.y > 0) {
        [self.tableView setContentOffset:CGPointMake(0, 0) animated:NO];
    }else{
        notNeedSetTableViewOffset = NO;
    }
    [self.tableView.mj_footer endRefreshing];
    [self setTableiewFooterViewStateFor:self.tableView  datasourceCount:self.datasource.count];
}

#pragma mark - UISearchControllerDelegate / UISearchResultsUpdating
//将要输入
- (void)willPresentSearchController:(UISearchController *)searchController
{
    [UIView animateWithDuration:0.25 animations:^{
        self.mapView.height += self.searchController.searchBar.height;
        self.mapView.top -= self.searchController.searchBar.height;
        self.pointImageView.bottom = self.mapView.height / 2.0;
    } completion:^(BOOL finished) {
    
    }];
}

//将要退出搜索框
- (void)willDismissSearchController:(UISearchController *)searchController
{
    [UIView animateWithDuration:0.25 animations:^{
        self.mapView.height -= self.searchController.searchBar.height;
        self.mapView.top += self.searchController.searchBar.height;
        self.pointImageView.bottom = self.mapView.height / 2.0;
    } completion:^(BOOL finished) {
        
    }];
}

//搜索框正在输入
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSString *key = searchController.searchBar.text;
    [self.searchResultsController requestDataWithKeyword:key];
}


- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction{
    if (wasUserAction == YES) {
        self.startPage = @"1";
        [self.datasource removeAllObjects];
        currentLong = self.mapView.region.center.longitude;
        currentLat = self.mapView.region.center.latitude;
        selectedRow = 0;
        self.tableView.hidden = YES;
        [self.indicatorView startAnimating];
        [self getCurrentLocationAddress];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;
    if (indexPath.row == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"currentAddressCell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"currentAddressCell"];
        }
    }else{
        cell = [tableView dequeueReusableCellWithIdentifier:@"locationCell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"locationCell"];
        }
    }
    
    AMapPOI *poi = self.datasource[indexPath.row];
    cell.textLabel.text = indexPath.row == 0 ? poi.address : poi.name;
    cell.textLabel.textColor = [UIColor colorWithHexString:@"#1c1c1c"];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.text = poi.address;
    cell.detailTextLabel.textColor = [UIColor colorWithHexString:@"#767676"];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    
    cell.layer.borderColor = kBDColorGray.CGColor;
    cell.layer.borderWidth = 0.5;
    
    if (indexPath.row == selectedRow) {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"duihao"]];
        imageView.frame = CGRectMake(0, 0, 20, 20);
        cell.accessoryView = imageView;
    }else{
        cell.accessoryView = nil;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    selectedRow = indexPath.row;
    AMapPOI *poi = self.datasource[indexPath.row];
    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude) animated:YES];
    [self.tableView reloadData];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([scrollView isKindOfClass:[UITableView class]]) {
        CGFloat of = scrollView.contentOffset.y;
        if (of <= 0) {
            CGFloat mapHeight = kBDScreenHeight / 3.0 - of - self.searchBar.bottom;
            self.mapView.height = mapHeight > (kBDScreenHeight / 3.0 * 2 - self.searchBar.bottom) ? kBDScreenHeight / 3.0 * 2 - self.searchBar.bottom : mapHeight;
            self.pointImageView.centerX = self.mapView.width / 2.0;
            self.pointImageView.bottom = self.mapView.height / 2.0;
            self.indicatorView.top = self.mapView.bottom;
        }
    }
}

- (UISearchBar *)searchBar{
    if (!_searchBar) {
        self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, 44.0)];
        _searchBar.placeholder = ASLocalizedString(@"输入商家");
        _searchBar.backgroundImage = [[UIImage alloc] init];
        _searchBar.delegate = self;
        [_searchBar setImage:[UIImage imageNamed:@"sousuo"]
                forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
        
        for (UIView *view in _searchBar.subviews) {
            if ([view isKindOfClass:NSClassFromString(@"UIView")]&&view.subviews.count>0) {
                view.backgroundColor = [UIColor colorWithHexString:@"#efeff4"];
                [[view.subviews objectAtIndex:0] removeFromSuperview];
                break;
            }
        }
        
        UITextField *searchField=[_searchBar valueForKey:@"_searchField"];
        searchField.textColor=[UIColor colorWithHexString:@"#4c4c4c"];
        searchField.font = [UIFont systemFontOfSize:13];
        //改变placeholder的颜色
        [searchField setValue:[UIColor colorWithHexString:@"#999999"] forKeyPath:@"_placeholderLabel.textColor"];
    }
    return _searchBar;
}

- (MAMapView *)mapView{
    if (!_mapView) {
        self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, self.searchBar.bottom, kBDScreenWidth, kBDScreenHeight / 3.0 * 2 - self.searchBar.bottom)];
        //        _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _mapView.delegate = self;
        _mapView.centerCoordinate = CLLocationCoordinate2DMake(23.117055306224895, 113.2759952545166);
        _mapView.showsUserLocation = YES;
        _mapView.showsCompass = NO;
        _mapView.showsScale = NO;
        MAUserLocationRepresentation *locationRepresntation = [[MAUserLocationRepresentation alloc] init];
        locationRepresntation.showsAccuracyRing = YES;
        [_mapView updateUserLocationRepresentation:locationRepresntation];
        _mapView.zoomLevel = 14.2;
        _mapView.minZoomLevel = 5;
        _mapView.maxZoomLevel = 20;
        _mapView.layer.borderColor = kBDColorGray.CGColor;
        _mapView.layer.borderWidth = 0.5;
        [_mapView addSubview:self.pointImageView];
        _pointImageView.centerX = _mapView.width / 2.0;
        _pointImageView.bottom = _mapView.height / 2.0;
    }
    return _mapView;
}

- (UIImageView *)pointImageView{
    if (!_pointImageView) {
        self.pointImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"location_datouzhen"]];
        _pointImageView.size = CGSizeMake(30, 30);
    }
    return _pointImageView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kBDScreenHeight / 3.0, kBDScreenWidth, kBDScreenHeight / 3.0 * 2) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.contentInset = UIEdgeInsetsMake(kBDScreenHeight / 3.0, 0, 0, 0);
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            notNeedSetTableViewOffset = YES;
            [self requestData];
        }];
    }
    return _tableView;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray array];
    }
    return _datasource;
}

- (UIActivityIndicatorView *)indicatorView{
    if (!_indicatorView) {
        self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicatorView.hidesWhenStopped = YES;
        _indicatorView.frame = CGRectMake(0, self.mapView.bottom, kBDScreenWidth, 50);
        [self.view addSubview:_indicatorView];
    }
    return _indicatorView;
}

- (UISearchController *)searchController {
    if (_searchController == nil) {
        _searchController = [[UISearchController alloc]initWithSearchResultsController:self.searchResultsController];
        _searchController.searchResultsUpdater = self;
        _searchController.dimsBackgroundDuringPresentation = YES;
        _searchController.delegate = self;
        [_searchController.searchBar sizeToFit];
        _searchController.searchBar.placeholder = ASLocalizedString(@"搜索地点");
    }
    return _searchController;
}

- (BDSearchResultsViewController *)searchResultsController{
    if (!_searchResultsController) {
        self.searchResultsController = [[BDSearchResultsViewController alloc] init];
    }
    return _searchResultsController;
}

- (AMapSearchAPI *)search{
    if (!_search) {
        self.search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
    }
    return _search;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
